package com.example.loginmvvm.taobao

import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.loginmvvm.base.LoadState
import com.example.loginmvvm.domain.OnSellDate
import kotlinx.coroutines.launch

/*
 * class title: 
 * Author by RenChunLin, Email 18957806320@163.com, Date on 2021/4/21.
 * PS: Not easy to write code, please indicate.
 */
class OnSellViewModel : ViewModel() {

    val contentList =
        MutableLiveData<MutableList<OnSellDate.TbkDgOptimusMaterialResponse.ResultList.MapData>>()

    val loadState = MutableLiveData<LoadState>()

    private val onSellRepository by lazy {
        OnSellRepository()
    }

    companion object {
        //默认第一页
        const val DEFAULT_PAGE = 1
    }

    //当前页
    private var mCurrentPage = DEFAULT_PAGE

    private var isLoadMore = false

    /**
     * 加载更多内容
     */
    fun loaderMore() {
        isLoadMore = true
        //去加载更多的内容
        LoadState.LOADER_MORE_LOADING
        mCurrentPage++
        this.listContentByPage(mCurrentPage)
    }

    /**
     * 加载内容
     */
    fun loadContent() {
        isLoadMore = false
        loadState.value = LoadState.LOADING
        this.listContentByPage(mCurrentPage)
    }

    private fun listContentByPage(page: Int) {
        //通过挂起的方式，免去了回调
        viewModelScope.launch {
            try {
                val onSellList = onSellRepository.getOnSellList(page)
                val oldValue = contentList.value ?: mutableListOf()
                oldValue.addAll(onSellList.tbk_dg_optimus_material_response.result_list.map_data)
                contentList.value = oldValue
                if (onSellList.tbk_dg_optimus_material_response.result_list.map_data.isEmpty()) {
                    loadState.value =
                        if (isLoadMore) LoadState.LOADER_MORE_EMPTY else LoadState.EMPTY
                } else {
                    loadState.value = LoadState.SUCCESS
                }
            } catch (e: Exception) {
                mCurrentPage--
                e.printStackTrace()
                if (e is NullPointerException) {
                    //没有更多内容的时候，会有一个空指针回来
                    loadState.value = LoadState.LOADER_MORE_EMPTY
                } else {
                    loadState.value =
                        if (isLoadMore) LoadState.LOADER_MORE_ERROR else LoadState.ERROR
                }
            }
        }
    }
}